<?php

class Core_Api_Config
{
	/**
	 * @param array
	 */
	protected $_vars = NULL;

	/**
	 * default constructor
	 */
	function __construct()
	{
		$this -> _table = Nuo::getT('core_config');
		$this -> load();
	}

	public function load()
	{
		$key = 'core/config';

		if (FALSE == ($data = Nuo_Cache::instance()-> read($key)))
		{
			$table = Nuo::getTable('core/config');

			$rows = $table -> fetchAll();

			$data = array();

			foreach ($rows as $row)
			{

				$group = $row -> data_group;
				$key = $row -> data_key;

				switch($row->data_type)
				{
					case 'array' :
					case 'json' :
						$data[$group][$key] = json_decode($row -> data_value, 1);
						break;
					default :
						$data[$group][$key] = $row -> data_value;
				}
			}

			Nuo_Cache::instance()-> write($key, $data);
		}
		$this -> _vars = $data;
	}

	/**
	 * @param string $name
	 * @param mixed $value
	 * @return mixed
	 */
	function read($group, $key = NULL)
	{
		if (NULL == $key)
		{
			return $this -> _vars[$group];
		}

		return $this -> _vars[$group][$key];
	}

	/**
	 * @param  string  $groupKey
	 * @param  array   $data
	 */
	function write($data)
	{
		$table = Nuo::getTable('core/config');

		foreach ($data as $name => $value)
		{
			if (substr($key, 0, 1) == '_')
			{
				continue;
			}

			if (substr($key, 0, 1) == '_')
			{
				continue;
			}

			list($module, $group, $key) = explode('_', $name, 3);

			if (!$key)
			{
				continue;
			}

			$group = $module . '/' . $group;

			$select = $table -> select() -> where('data_key=?', $key) -> where('data_group=?', $group) -> where('module_id=?', (string)$module);

			$row = $table -> fetchRow($select);

			if ($row)
			{
				switch($row->data_type)
				{
					case 'array' :
					case 'json' :
						$row -> data_value = json_encode($value);
						break;
					default :
						$row -> data_value = $value;
						break;
				}
				$row -> save();
			}
		}
	}

}
